Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
I need to filter hyphen(-) and space(" ") in my string, what am I doing wrong?

This is the code I am using (but it only works for hyphens not for spaces)

console.log(
    "some - text".replace(/\s\-/g, '').toLowerCase()
)

Can anyone point out what is wrong in this RegEx ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The regex you have removes the space and the dash, leaving the second space

You need other regex to remove all spaces

console.log(
    "some - text".replace(/\s\-/g, '') // space and dash
)

console.log(
    "some - text".replace(/\s-\s/g, '') // space before and after a dash
)


console.log(
    "some     -        text".replace(/\s+\-\s+/g, '') // any whitespace before and after
)


console.log(
    "so- me     -        te-xt".replace(/\s|-/g, '') // all spaces and all dashes, can be written as a acharacter class [\s-]
)

about 4 years ago · Juan Pablo Isaza Report

0

Use\W for non-word character:

console.log("some - text".replace(/\W/g, '').toLowerCase())
about 4 years ago · Juan Pablo Isaza Report

0

Your regex is matching "(1 occurrence of some space)(definitely followed by 1 occurrence of ad ash)". You want it to match any occurrence of those, so use a character class in your regex (see: MDN WebDocs: JavaScript Character Classes, with brackets, /[\s\-]/g, like so:

console.log(
    "some - text".replace(/[\s-]/g, '').toLowerCase()
)

Want to replace another character? Just throw it into the class and you're good to go.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!